import base64
import json
from flask import Blueprint, render_template, redirect, make_response, jsonify, session
from flask import request
# from app import app
from development import SECRETKEY
import requests
import development as dp
from flask_jwt_extended import create_access_token,jwt_required, get_jwt_identity,verify_jwt_in_request

bp = Blueprint("userInfo", __name__, url_prefix='/userinfo')
from mongoDb_connection.connection import initDatabase, addData, find_data, update_data



@bp.route('/getUserInfo', methods=['GET', 'POST'])
def getInfo():
    db = initDatabase(dp.DATABASE_NAME)
    verify_jwt_in_request()
    current_user = get_jwt_identity()
    # print(current_user)
    find_json = {
        "openid": current_user
    }
    findData = find_data(db, find_json, 'one', 'userInfo')
    img1 = findData['avatarUrl']
    findData['avatarUrl'] = return_img_stream(img1)
    # print(findData)
    findData['_id'] = str(findData['_id'])
    returnData = JSONEncoder().encode(findData)
    # print(str(findData['_id']))
    return returnData

@bp.route('/updateUserInfo', methods=['GET', 'POST'])
def updateInfo():
    db = initDatabase(dp.DATABASE_NAME)
    verify_jwt_in_request()
    current_user = get_jwt_identity()
    findJson = {
        'openid': current_user
    }
    # print(request.json)
    updateJson = request.json
    ans = update_data(db, findJson, updateJson, 'one', 'userInfo')
    if ans['res'] == 'update_success':
        print("success_update")
        return {'msg': "保存成功", 'code': 200}
    else:
        return {'msg': "数据库更新失败", 'code': 200}